package com.yuanfeng.business.service.impl;


import com.alibaba.csp.sentinel.util.StringUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.yuanfeng.business.dto.*;
import com.yuanfeng.business.entity.ShopBaseEntity;
import com.yuanfeng.business.entity.ShopMessageLogEntity;
import com.yuanfeng.business.feign.*;
import com.yuanfeng.business.mapper.*;
import com.yuanfeng.business.service.ShopBaseService;
import com.yuanfeng.business.service.ShopEvaluationService;
import com.yuanfeng.business.vo.*;
import com.yuanfeng.commoms.aspect.UserPermissionsResult;
import com.yuanfeng.commoms.aspect.UserService;
import com.yuanfeng.commoms.config.PermissionsConstant;
import com.yuanfeng.commoms.config.YFConfig;
import com.yuanfeng.commoms.constant.CommonStatusEnum;
import com.yuanfeng.commoms.constant.CommonType;
import com.yuanfeng.commoms.constant.RedisConstants;
import com.yuanfeng.commoms.dto.goods.CommonShopStateDTO;
import com.yuanfeng.commoms.dto.goods.ShopListQueryDTO;
import com.yuanfeng.commoms.dto.shop.*;
import com.yuanfeng.commoms.dto.userms.UserInfoDTO;
import com.yuanfeng.commoms.dto.userms.UserTokenBeanDTO;
import com.yuanfeng.commoms.exception.BizCodeEnume;
import com.yuanfeng.commoms.rocketmq.MqSendUtils;
import com.yuanfeng.commoms.util.*;
import com.yuanfeng.commoms.util.Json.JsonUtils;
import com.yuanfeng.commoms.util.excel.Constants;
import com.yuanfeng.commoms.util.excel.ExcelsUtil;
import com.yuanfeng.commoms.util.querypage.PageUtils;
import com.yuanfeng.commoms.util.querypage.Query;
import com.yuanfeng.commoms.util.secverifyapiutil.Base64Utils;
import com.yuanfeng.commoms.vo.base.BaseSysConfigsVO;
import com.yuanfeng.commoms.vo.goods.GdsListQueryResultVO;
import com.yuanfeng.commoms.vo.shop.*;
import com.yuanfeng.commoms.vo.user.UserInfoVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Administrator
 */
@Service
public class ShopBaseServiceImpl extends ServiceImpl<ShopBaseMapper, ShopBaseEntity>
        implements ShopBaseService {
    private final static Logger log = LoggerFactory.getLogger(ShopBaseServiceImpl.class);


    @Resource
    private ShopBaseMapper shopBaseMapper;

    @Autowired
    private GoodsServiceClient goodsServiceClient;

    @Resource
    private ShopNavMapper shopNavMapper;

    @Resource
    private ShopSelfCatMapper shopSelfCatMapper;

    @Autowired
    private BaseServiceClient baseServiceClient;

    @Autowired
    private OrderServiceClient orderServiceClient;

    @Value("${domainName}")
    private  String domainName ;

    @Autowired
    private UsermsServiceClient usermsServiceClient;

    @Autowired
    private ThirdPartyServiceClient thirdPartyServiceClient;

    @Resource
    private ShopGoodsCatMapper shopGoodsCatMapper;

    @Resource
    private ShopClassBindMapper shopClassBindMapper;

    @Resource
    private ShopJoinBaseMapper joinBaseMapper;

    @Resource
    private ShopCashOnDeliveryMapper shopCashOnDeliveryMapper;

    @Resource
    private ShopJoinPayMapper shopJoinPayMapper;

    @Resource
    private ShopGateMapper shopGateMapper;

    @Resource
    private ShopMessageLogMapper shopMessageLogMapper;

    @Resource
    private ShopCompanyMapper shopCompanyMapper;
    @Resource
    private ShopRetentionMoneyRecordMapper shopRetentionMoneyRecordMapper;

    @Resource
    private ShopEvaluationService shopEvaluationService;
    @Override
    public List<ArticleShopDTO> selectAllShop() {
        return shopBaseMapper.selectAllShop();
    }

    @Override
    public WebShopListQueryEsDTO selectByShopId2(Integer shopId) {
        return shopBaseMapper.selectByShopId2(shopId);
    }

    @Override
    public ShopListQueryDTO selectByH5ShopId(Integer shopId) {
        return shopBaseMapper.selectByH5ShopId(shopId);
    }

    @Override
    public ResponseResult checkTheStatus(UserTokenBeanDTO userTokenBeanDTO) {
        UserInfoVO userInfo = null;
        if(StringUtils.isNotBlank(userTokenBeanDTO.getToken())) {
            userInfo = ParseTokenUtils.getUserInfoByTokenNoIsExist(userTokenBeanDTO.getToken());// 获取user信息
            if(userInfo != null){
                String shopId = userInfo.getShopId();
                if(null == shopId   || "".equals(shopId)){//shopid 为null是普通用户
                    return ResponseResult.fail(2,"","您不是商家或供应商");
                }
                Integer shopType = shopBaseMapper.checkTheStatus(shopId);
                if(null != shopType){
                    if(shopType == 1){
                        //是商家
                        return ResponseResult.success("是商家",shopType);
                    }else if(shopType == 2){
                        //供应商
                        return ResponseResult.success("是供应商",shopType);
                    }else{
                        return ResponseResult.fail(2,null,"您不是商家或供应商");
                    }
                }else{
                    // 是门店用户
                    return ResponseResult.fail(2,"","未登录");
                }
            }
        }
        return ResponseResult.fail(2,"","未登录");
    }

    @Override
    public InvoiceSwitchEntityVO queryShopInvoiceSwitch(Map<String, Object> paramTmp) {
        return this.baseMapper.queryShopInvoiceSwitch(paramTmp);
    }

    @Override
    public GdsShopDetailResultVO queryShopinfoByShopId(Integer shopId) {
        return this.baseMapper.queryShopinfoByShopId(shopId);
    }

    @Override
    public ResponseResult selectByShopId(Integer shopId) {
        ShopIndexVO shopIndex = this.baseMapper.selectByParam(shopId);
        String address = baseServiceClient.getAddressString(shopIndex.getShopProvince(),shopIndex.getShopCity(),shopIndex.getShopArea()).getData().toString();
        shopIndex.setShopCompanyAddress(address+shopIndex.getShopAddress());
        return ResponseResult.success(shopIndex);
    }

    @Override
    public ResponseResult updateShopCollect(Map<String, String> paraMap) {
         this.baseMapper.updateShopCollect(paraMap);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult checkShopNameExist(String shopName) {
        ResponseResult rr;
        Integer isExist = 1;
        Integer count1 = 0;
        Integer count2 = 0;
        try {
            count1 = shopBaseMapper.queryShopNameCount(shopName);
            count2 = shopBaseMapper.queryShopNameJoinCount(shopName);
            if (count1 == 0 && count2 == 0) {
                isExist = 0;
            }
            rr = ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL.getMsg(),isExist);
        }catch (Exception e){
            log.error(e.getMessage());
            rr = ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.QUERY_ERROR.getMsg());
        }
        return rr;
    }

    @Override
    @Transactional
    public ResponseResult deleteShopClassBind(ShopClassBindQueryDTO shopClassBindQueryDTO) {

        Integer cat_parent_id = goodsServiceClient.queryParentCatId(shopClassBindQueryDTO);
        Integer count = goodsServiceClient.queryChildCount(cat_parent_id);
        shopBaseMapper.deleteShopBindProduct(shopClassBindQueryDTO);
        if (null != count && count <= 1) {
            shopClassBindQueryDTO.setProductClassId(cat_parent_id);
            shopBaseMapper.deleteShopBindProduct(shopClassBindQueryDTO);
        }
        return ResponseResult.success();
    }


    @Override
    @Transactional
    public ResponseResult deleteShopClassBindBatch(ShopClassBindBatchDeleteDTO param) {
        List<Integer> productClassIds = param.getProductClassIds();
        try {
            if (null != productClassIds && productClassIds.size() > 0) {
                for (Integer productClassId : productClassIds) {
                    ShopClassBindQueryDTO param1 = new ShopClassBindQueryDTO();
                    param1.setJoinId(param.getJoinId());
                    param1.setShopClassBindId(param.getShopClassBindId());
                    param1.setProductClassId(productClassId);
                    param1.setShopId(param.getShopId());
                    Integer cat_parent_id = goodsServiceClient.queryParentCatId(param1);
                    Integer count = goodsServiceClient.queryChildCount(cat_parent_id);
                    shopBaseMapper.deleteShopBindProduct(param1);
                    if (null != count && count <= 1) {
                        param1.setProductClassId(cat_parent_id);
                        shopBaseMapper.deleteShopBindProduct(param1);
                    }
                }
            }
        }catch (Exception e){
            log.error(e.getMessage());
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.DELETE_ERROR.getMsg());
        }
        return ResponseResult.success();
    }

    @Override
    @Transactional
    public ResponseResult updateShopClassBindBatch(GdbMerchantClassBindDTO param) {
        ManageShopCatMenuVO currentCat = new ManageShopCatMenuVO();
        if (!RedisUtil.exists(RedisConstants.FKGOU_USER_TOKEN_USER + param.getToken())) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        param.setShopId(userInfo.getShopId()==null?0: Integer.valueOf(userInfo.getShopId()));
        List<Integer> productClassIds = param.getProductClassIds();
        List<ManageShopCatMenuVO> currentCatList = new ArrayList<>();
        for(Integer productClassId:productClassIds) {
            param.setProductClassId(productClassId);
            // 增加类目佣金
            if (null != param.getProductClassId()) {
                CommissionRateBeanVO commissionRateBean = shopBaseMapper.selectCommissionRate(param.getProductClassId());
                if(null != commissionRateBean){
                    param.setCommissionRate(commissionRateBean.getCatCommission());
                }
                param.setShopClassBindEnable(1);
                currentCat = shopBaseMapper.selectByCatId2(param.getProductClassId());
                currentCatList.add(currentCat);
                param.setProductCatIds(currentCat.getCatId().toString());
                if (null != currentCat && currentCat.getCatLevel() == 3) {
                    param.setProductCatIds(currentCat.getCatId().toString());
                    param.setCommissionRate(new BigDecimal(currentCat.getCatCommission()));
                    shopBaseMapper.insertOrUpdateSelective(param);//添加或修改经营类目
                }
            }
        }
        return ResponseResult.success(currentCatList);
    }

    @Override
    public ShopUserMessageResultVO queryUserId(Integer shopId) {
        ShopUserMessageResultVO result = shopBaseMapper.selectUserIdByShopId(shopId);
        if(null != result){
            result.setContactsPhone(result.getShopTel());
        }
        return result;
    }

    @Override
    public ResponseResult queryShopIndex(WebShopGoodsListQueryDTO param) {
        param.setCurrentPage((param.getPage() - 1) * param.getLimit());
        Integer shopId = param.getShopId();

        // 查询店铺信息
        WebShopBaseIndexVO shopBase = shopBaseMapper.selectWebIndex(shopId);

        if (null == shopBase) {
            return ResponseResult.fail(0, "店铺信息为空");
        }
        WebShopIndexResultVO shopIndexResult = new WebShopIndexResultVO();
        // 获取店铺导航
        List<GdbMerchantShopNavQueryVO> shopNav = shopNavMapper.selectShopNavByShopId(shopId);
        // 查询店铺自定义分类
        List<ManageShopSelfCatMenuVO> rootMenus = shopSelfCatMapper.selectByShopId(shopId);
        // 获取多级分类
        List<ManageShopSelfCatMenuVO> shopSeltCatList  = getMenuList(rootMenus);
        // 处理轮播信息
        dealShopSlide(shopBase);

        String configValue = null;

        if (shopBase.getShopImage() == null || shopBase.getShopImage().equals("") || shopBase.getShopLogo() == null
                || shopBase.getShopLogo().equals("") || shopBase.getWapShopLogo() == null
                || shopBase.getWapShopLogo().equals("")) {
            configValue = baseServiceClient.selectConfigValueFeign("logo_copywriting_ico_shop");

            if (shopBase.getShopImage() == null || shopBase.getShopImage().equals("")) {
                shopBase.setShopImage(configValue);
            }
            if (shopBase.getShopLogo() == null || shopBase.getShopLogo().equals("")) {
                shopBase.setShopLogo(configValue);
            }
        }

        WebIndexRecommendQueryParamVO recommendParam = new WebIndexRecommendQueryParamVO();
        recommendParam.setShopId(shopId);

        // 热销商品排行
        recommendParam.setOpType(3);
        recommendParam.setLimitSize(4);
        List<GdsListQueryResultVO> hotGoods = this.baseMapper.selectWebShopIndex(recommendParam);

        // 收藏量
        recommendParam.setOpType(2);
        recommendParam.setLimitSize(4);
        List<GdsListQueryResultVO> collectGoods = this.baseMapper.selectWebShopIndex(recommendParam);

        // 推荐商品
        recommendParam.setCurrentPage(param.getPage());
        recommendParam.setLimitSize(param.getLimit());
        List<GdsListQueryResultVO> recommendGoods = this.baseMapper.selectWebShopIndex(recommendParam);
        for (GdsListQueryResultVO recommendGood : recommendGoods) {
            recommendGood.setGoodsIdOne(Integer.parseInt(recommendGood.getGoodsId()));
        }
        Integer totalCount = this.baseMapper.selectWebShopIndexCount(recommendParam);

        shopIndexResult.setHotGoods(hotGoods);
        shopIndexResult.setCollectGoods(collectGoods);
        shopIndexResult.setRecommendGoods(recommendGoods);
        shopIndexResult.setShopBase(shopBase);
        shopIndexResult.setShopSeltCatList(shopSeltCatList);
        shopIndexResult.setShopNav(shopNav);
        shopIndexResult.setTotalCount(totalCount);

        return ResponseResult.success(shopIndexResult);
    }
    private void dealShopSlide(WebShopBaseIndexVO shopBase) {
        // 处理轮播信息
        String shopSlide = shopBase.getShopSlide();
        if (null != shopSlide && !shopSlide.equals("")) {
            String[] shopSlideurlArr = shopBase.getShopSlideurl().split(",", -1);
            String[] shopSlideArr = shopSlide.split(",", -1);
            List<ShopSlideurlResultVO> shopSlideurlList = Lists.newArrayList();

            for (String shopSlideurl : shopSlideurlArr) {
                ShopSlideurlResultVO slideUrlList = new ShopSlideurlResultVO();
                if (!shopSlideurl.equals("https:\\") && !shopSlideurl.equals("http://")) {

                    if (shopSlideurl.contains("goodsId") && !shopSlideurl.contains("type=goods")) {
                        String[] gidStrings = shopSlideurl.split("goodsId=");
                        int goodsId = Integer.parseInt(gidStrings[gidStrings.length - 1]);
                        CommonAndGoodsQueryVO commonIdAndGoodsId = new CommonAndGoodsQueryVO();
                        Integer commonId = this.baseMapper.selectCommonId(goodsId);
                        commonIdAndGoodsId.setGoodsId(goodsId);
                        commonIdAndGoodsId.setCommonId(commonId);
                        // 跳转商品
                        slideUrlList.setOpType(2);
                        slideUrlList.setCommonIdAndGoodsId(commonIdAndGoodsId);
                    } else if (shopSlideurl.contains("shopId")) {
                        String[] gidStrings = shopSlideurl.split("shopId=");
                        int shopId = Integer.parseInt(gidStrings[gidStrings.length - 1]);
                        // 跳转店铺
                        slideUrlList.setOpType(4);
                        slideUrlList.setShopId(shopId);
                    } else if (shopSlideurl.contains("catId")) {
                        String[] gidStrings = shopSlideurl.split("catId=");
                        int catId = Integer.parseInt(gidStrings[gidStrings.length - 1]);
                        // 跳转店铺
                        slideUrlList.setOpType(6);
                        slideUrlList.setCatId(catId);
                    } else if (shopSlideurl.contains("images.oss")) {
                        // 跳转店铺
                        slideUrlList.setOpType(3);
                        slideUrlList.setUrl(shopSlideurl);
                    } else {
                        String[] gidStrings = shopSlideurl.split("gid=");
                        if (shopSlideurl.contains("gid") && !shopSlideurl.contains("type") && null != gidStrings
                                && !gidStrings.equals("")) {

                            int goodsId = Integer.parseInt(gidStrings[gidStrings.length - 1]);
                            CommonAndGoodsQueryVO commonIdAndGoodsId = new CommonAndGoodsQueryVO();
                            Integer commonId = this.baseMapper.selectCommonId(goodsId);
                            commonIdAndGoodsId.setGoodsId(goodsId);
                            commonIdAndGoodsId.setCommonId(commonId);
                            // 跳转商品
                            slideUrlList.setOpType(2);
                            slideUrlList.setCommonIdAndGoodsId(commonIdAndGoodsId);
                        } else {
                            if (shopSlideurl.contains("gid=") && shopSlideurl.contains("type=goods")) {
                                String[] amp = shopSlideurl.split("&amp;");
                                String gid = "";
                                Integer goodsId = null;
                                for (String str : amp) {
                                    if (str.contains("gid=")) {
                                        gid = str;
                                    }
                                }
                                if (null != gid && !gid.equals("")) {
                                    goodsId = Integer.parseInt(gid.split("=")[1]);
                                    CommonAndGoodsQueryVO commonIdAndGoodsId = new CommonAndGoodsQueryVO();
                                    Integer commonId = this.baseMapper.selectCommonId(goodsId);
                                    commonIdAndGoodsId.setGoodsId(goodsId);
                                    commonIdAndGoodsId.setCommonId(commonId);
                                    // 跳转商品
                                    slideUrlList.setOpType(2);
                                    slideUrlList.setCommonIdAndGoodsId(commonIdAndGoodsId);
                                } else {
                                    slideUrlList.setOpType(7);
                                }

                            } else if (shopSlideurl.contains("type") && !shopSlideurl.contains("gid=")) {
                                // 跳转活动页
                                slideUrlList.setOpType(8);
                                slideUrlList.setActivityPage(shopSlideurl);
                            } else {
                                slideUrlList.setOpType(7);
                            }

                        }
                    }

                } else {
                    slideUrlList.setOpType(7);
                }
                shopSlideurlList.add(slideUrlList);
            }

            for (int i = 0; i < shopSlideArr.length; i++) {

            }
            Integer length = shopSlideArr.length;
            List<ShopSlideurlResultVO> slideurlList = Lists.newArrayList();
            if (length.equals(shopSlideurlList.size())) {
                for (int i = 0; i < shopSlideurlList.size(); i++) {
                    if (!shopSlideArr[i].equals("")) {
                        shopSlideurlList.get(i).setShopSlideUrl(shopSlideArr[i]);
                        slideurlList.add(shopSlideurlList.get(i));
                    }
                }
            }

            shopBase.setShopSlideurlList(slideurlList != null ? slideurlList : new ArrayList<ShopSlideurlResultVO>());

        } else {
            shopBase.setShopSlideurlList(new ArrayList<ShopSlideurlResultVO>());
        }
    }
    /**
     * 找出一级菜单和二级菜单
     *
     * @param rootMenus
     * @return
     */
    public List<ManageShopSelfCatMenuVO> 	getMenuList(List<ManageShopSelfCatMenuVO> rootMenus) {
        List<ManageShopSelfCatMenuVO> list = new ArrayList<ManageShopSelfCatMenuVO>();
        // 先找到所有的一级菜单
        for (int i = 0; i < rootMenus.size(); i++) {
            ManageShopSelfCatMenuVO menu = rootMenus.get(i);
            // 一级菜单 没有父节点
            if (menu.getParentId() == 0) {
                list.add(menu);
            }
        }

        // 查找二级菜单
        /**
         * 利用递归找出所有子菜单
         */
        for (ManageShopSelfCatMenuVO menu : list) {
            menu.setChildren(getChild(menu.getShopGoodsCatId(), rootMenus));
        }

        return list;

    }
    /**
     * 找出子菜单
     *
     * @param rootMenu
     * @return
     */
    private List<ManageShopSelfCatMenuVO> getChild(Integer parentId, List<ManageShopSelfCatMenuVO> rootMenu) {
        // 子菜单
        List<ManageShopSelfCatMenuVO> childList = new ArrayList<ManageShopSelfCatMenuVO>();

        for (ManageShopSelfCatMenuVO menu : rootMenu) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (!org.springframework.util.StringUtils.isEmpty(menu.getParentId())) {
                if (menu.getParentId().equals(parentId)) {
                    childList.add(menu);
                }
            }
        }

        // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }

        // 把子菜单的子菜单再循环一遍
        for (ManageShopSelfCatMenuVO menu : childList) {
            // 递归
            menu.setChildren(getChild(menu.getShopGoodsCatId(), rootMenu));
        }

        return childList;
    }

    @Override
    public ResponseResult queryByShopIdFind(Map<String, String> map) {
        if (null != map.get("shopId")  ){
            Integer shopId = Integer.parseInt((String)map.get("shopId"));
            //查询店铺 店招等
            Map<String, Object> favoritesshopTime = this.baseMapper.queryByShopIdFind(shopId);
            if(null != favoritesshopTime && (null == favoritesshopTime.get("shopBanner") || "" .equals(favoritesshopTime.get("shopBanner")))){
                String shopBanner = "/files/images/pc/shop-default.png";
                shopBanner = domainName + shopBanner;
                favoritesshopTime.put("shopBanner",shopBanner);
            }
            ResponseResult resultResp = usermsServiceClient.checkFavoriteShopOrNot(map);//判断当前用户是否收藏店铺
            if(null != resultResp && 1 == resultResp.getCode()){
                Integer type  =(Integer) resultResp.getData();
                favoritesshopTime.put("type",type);
            }else {
                favoritesshopTime.put("type",0);
            }
            return ResponseResult.success(favoritesshopTime);
        }

        return ResponseResult.fail(BizCodeEnume.VALID_EXCEPTION.getCode(),BizCodeEnume.VALID_EXCEPTION.getMsg());
    }

    @Override
    public ShopBaseEntity queryShopStatus(Map<String, String> map) {
        QueryWrapper<ShopBaseEntity> queryWrapper = new QueryWrapper<>();
        if (null != map && null != map.get("userId")) {
            queryWrapper.eq("user_id", map.get("userId"));
        }
        if (null != map && null != map.get("shopStatus")) {
            queryWrapper.eq("shop_status", map.get("shopStatus"));
        }
        if (null != map && null != map.get("shopType")) {
            queryWrapper.eq("shop_type", map.get("shopType"));
        }
        ShopBaseEntity shopBaseEntity = this.baseMapper.selectOne(queryWrapper);
        return shopBaseEntity;
    }

    @Override
    public ResponseResult queryShopInvoiceSwitchStatus(Map<String, Object> param) {
        Integer result = 0;
        try {
            InvoiceSwitchEntityVO data = this.baseMapper.queryShopInvoiceSwitch(param);
            Integer invoiceSwitchStatus = data.getInvoiceSwitchStatus();
            Integer invoiceAuditStatus = data.getInvoiceAuditStatus();
            if(1 == invoiceAuditStatus && 1 == invoiceSwitchStatus){
                result = 1;
            }else if(0 == invoiceAuditStatus && 1 == invoiceSwitchStatus){
                result = 1;
            }

            return ResponseResult.success(result);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseResult.fail(e.getMessage());
        }

    }

    @Override
    public ResponseResult queryOperateMessage(PersonMessageQueryDTO param) {
        if (!RedisUtil.exists(RedisConstants.FKGOU_USER_TOKEN_USER + param.getToken())) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }

        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        String shopId = userInfo.getShopId();
        OperateMessagQueryVO result = new OperateMessagQueryVO() ;
        if(null != shopId){
            result = shopBaseMapper.selectOperateMessage(Integer.valueOf(shopId));
        }
        if(null == result){
            result = new OperateMessagQueryVO();
        }
        Integer currentPage = param.getCurrentPage();
        Integer pageSize = param.getPageSize();
        currentPage = (currentPage - 1)*pageSize;
        param.setCurrentPage(currentPage);
        List<ShopClassBindQueryVO> classBindList = shopClassBindMapper.selectByShopIdOrJoinId(param);
        Integer totalCount = 0;
        totalCount = shopClassBindMapper.selectByShopIdOrJoinIdCount(param);
        // 查询所有分类
        List<GoodsCatsMenuListVO> rootMenus = shopGoodsCatMapper.selectAllCat3();

        for (ShopClassBindQueryVO classBind : classBindList) {
            List<String> catNames = getMenuList4(rootMenus, classBind.getProductClassId());
            classBind.setCatNames(catNames);
        }
        result.setClassBindList(classBindList);
        result.setTotalCount(totalCount);

        return ResponseResult.success(result);
    }

    /**
     * 根据子类id查所有父级名称
     *
     * @param rootMenus
     * @param catId
     * @return
     */
    public List<String> getMenuList4(List<GoodsCatsMenuListVO> rootMenus, Integer catId) {
        List<String> catNameList = Lists.newArrayList();

        for (GoodsCatsMenuListVO menu : rootMenus) {

            if (menu.getCatId().equals(catId)) {
                catNameList.add(menu.getCatName());
                catNameList = getChild4(menu.getCatParentId(), rootMenus, catNameList);
                break;
            }
        }

        return catNameList;

    }

    /**
     * 找出子菜单
     *
     * @param
     * @param rootMenu
     * @return
     */
    private List<String> getChild4(Integer parentId, List<GoodsCatsMenuListVO> rootMenu, List<String> catNameList) {
        // 子菜单

        for (GoodsCatsMenuListVO menu : rootMenu) {
            // 遍历所有节点，将父菜单id与传过来的id比较
            if (!org.springframework.util.StringUtils.isEmpty(menu.getCatParentId())) {
                if (menu.getCatId().equals(parentId)) {
                    catNameList.add(0, menu.getCatName());
                    if (!menu.getCatParentId().equals(0)) {
                        catNameList = getChild4(menu.getCatParentId(), rootMenu, catNameList);
                    }
                }
            }
        }

        return catNameList;
    }

    @Override
    public ResponseResult queryQualifications(Integer shopId) {
        WapShopBaseDetailVO shopBase = this.baseMapper.queryQualificationsByShopId(shopId);
        if (null == shopBase) {
            return ResponseResult.success("该店铺不存在或关闭");
        }

        return ResponseResult.success(shopBase);
    }

    @Override
    public ResponseResult checkIsSelfGoods(Map<String, Object> param) {
        Integer isSelf = 0;
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(String.valueOf(param.get("token")));
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        } else {
            param.put("userId",userInfo.getUserId());
        }
        try {
            Integer shopId = this.baseMapper.queryShopIdByUserId(param);
            if(null != shopId) {
                param.put("shopId", shopId);
                //1-商家；2-供应商
                Integer shopType = this.baseMapper.getShopType(param);
                if (1 == shopType) {
                    isSelf = this.baseMapper.checkShopSelf(param);
                    if (isSelf > 0) {
                        isSelf = 1;
                        return ResponseResult.fail(CommonStatusEnum.SUCCESS.getCode(),BizCodeEnume.NOT_BUY_ME_GOODS.getMsg(),isSelf);
                    }
                } else if (2 == shopType) {
                    isSelf = this.baseMapper.checkSupplySelf(param);
                    if (isSelf > 0) {
                        isSelf = 2;
                        return ResponseResult.fail(CommonStatusEnum.SUCCESS.getCode(),BizCodeEnume.NOT_BUY_ME_SUPPLIER_GOODS.getMsg(),isSelf);
                    }
                }
            }
            return ResponseResult.fail(isSelf);
        }catch (Exception e){
            return ResponseResult.fail(e.getMessage());
        }
    }

    @Override
    public ResponseResult queryShopTypeStatus(UserTokenBeanDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());
        if (null == userInfo) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }

        String shopId = userInfo.getShopId();
        ShopStatusQueryResultVO result = null;
        if (null == shopId ) {
            result = new ShopStatusQueryResultVO();
            result.setShopStatus(0);
            return ResponseResult.success(result);
        }
        if(null == userInfo.getSellerIsAdmin() && null != userInfo.getShopGateId()){//判断是否是门店
            GdbShopGatePoVO shopGate = shopGateMapper.queryShopGateId(userInfo.getShopGateId());
            //如果查询出的门店信息不为空就就手动封装参数 让门店跳转门店中心
            if(null != shopGate && null != shopGate.getShopGateId()){
                result = new ShopStatusQueryResultVO();
                result.setPaymentVerifyReason("通过");
                result.setPaymentVerifyStatus(2);
                result.setShopBusiness(1);
                result.setShopStatus(3);
                result.setShopVerifyReason("通过");
                result.setShopType(1);
            }
        }else{
            result = shopBaseMapper.selectShopStatus(shopId);
        }

        if (result != null ) {
            result.setSellerisAdmin(userInfo.getSellerIsAdmin());
        }

        if (null == result ) {
            result = new ShopStatusQueryResultVO();
            result.setShopStatus(0);
        }

        return ResponseResult.success(result);
    }

    @Override
    public ResponseResult queryFreeShipping(UserTokenBeanDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_SHOP_SETSHOP, param.getToken());
        BigInteger shopFreeShipping = null;
        if (userPermissionsResult.getFlag()) {
            Integer shopId = Integer.valueOf(userPermissionsResult.getShopId());
            shopFreeShipping = shopBaseMapper.selectFreeShipping(shopId);
        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        return ResponseResult.success(shopFreeShipping);
    }

    @Override
    public ResponseResult selfshopadd(Map<String, Object> param) throws IOException {
        if (org.springframework.util.StringUtils.isEmpty(param.get("userMobile")) || org.springframework.util.StringUtils.isEmpty(param.get("shopName")) ||
                org.springframework.util.StringUtils.isEmpty(param.get("shopProvince")) || org.springframework.util.StringUtils.isEmpty(param.get("shopCity")) || org.springframework.util.StringUtils.isEmpty(param.get("shopArea"))){
            return ResponseResult.fail(BizCodeEnume.MISSING_PARAMETER);
        }

        String userInfoStr = RedisUtil.get(YFConfig.YF_PLATFORM_TOKEN_USER + param.get("token"));

        if (null == userInfoStr || userInfoStr.equals("")) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        ResponseResult resultResp = usermsServiceClient.checkPhone(param);
        Map data = (Map) resultResp.getData();
        String start = String.valueOf(data.get("start"));
        Boolean selfShop = false;
        if (start.equals("1")){//已注册无店铺  要有验证码判断
            String phoneCode = String.valueOf(param.get("phoneCode"));
            String sessionPhoneCode = RedisUtil.get(YFConfig.YF_USER_RESTRICT + String.valueOf(param.get("userMobile")));
            if (sessionPhoneCode == null || sessionPhoneCode == ""){
                return ResponseResult.fail(BizCodeEnume.VERIFICATION_CODE_CANNOT_BE_EMPTY);
            }
            if (!phoneCode.equals(sessionPhoneCode)) {
                return ResponseResult.fail(BizCodeEnume.INCORRECT_VERIFICATION_CODE);
            }
            //短信校验后就删除
            RedisUtil.remove(YFConfig.YF_USER_RESTRICT + String.valueOf(param.get("userMobile")));
            //新增自营店铺
            selfShop = createSelfShop(param);
            if (selfShop){
                Map<String, Object> pwd = new HashMap<>();
                pwd.put("password",param.get("password"));
                pwd.put("userMobile",param.get("userMobile"));
                Integer integer = shopBaseMapper.forgotPassword(pwd);
            }
        } else if(start.equals("5")){//用户未注册
            HashMap<String, String> map = new HashMap<>();
            map.put("platForm","1");//客户来源
            map.put("userMobile",String.valueOf(param.get("userMobile")));
            map.put("phoneCode",String.valueOf(param.get("phoneCode")));
            map.put("password",String.valueOf(param.get("password")));
            ResponseResult register = usermsServiceClient.register(map);
            Map userData = (Map) resultResp.getData();

            //用户注册成功开始创建店铺
            if (register.getCode()==BizCodeEnume.REGISTRATION_SUCCESS.getCode()){
                //新增自营店铺
                selfShop = createSelfShop(param);
            }else{
                return register;
            }
        }
        if (selfShop){
            return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
        }else{
            return ResponseResult.fail(BizCodeEnume.REGISTERED_STORE_WITH_PHONE_NUMBER.getMsg());
        }
    }

    //插入店铺信息
    @Transactional
    public Boolean createSelfShop(Map<String, Object> param){
        String userId = shopBaseMapper.queryUserInfoUserId(String.valueOf(param.get("userMobile")));

        //向shopjoinbase表插入数据
        //获取joinId
        Map<String, Object> joinbase = new HashMap<>();
        Date currentDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String joinId = SnowflakeIdWorker.getSnowId();
        joinbase.put("joinId",joinId);
        joinbase.put("contactPhone",String.valueOf(param.get("userMobile")));
        joinbase.put("shopName",String.valueOf(param.get("shopName")));
        joinbase.put("shopProvince",String.valueOf(param.get("shopProvince")));
        joinbase.put("shopCity",String.valueOf(param.get("shopCity")));
        joinbase.put("shopArea",String.valueOf(param.get("shopArea")));
        joinbase.put("auditStatus",1);
        joinbase.put("shopType",1);
        joinbase.put("userId",userId);
        joinbase.put("createTime",new Date());
        joinbase.put("lastUpdateTime",new Date());
        joinBaseMapper.insertShopJoinBase(joinbase);

        //向shopbase表插入数据
        Map<String, Object> shopbase = new HashMap<>();
        shopbase.put("userId",userId);
        shopbase.put("shopName",String.valueOf(param.get("shopName")));
        shopbase.put("userName",String.valueOf(param.get("userMobile")));
        shopbase.put("shopClassId",0);
        shopbase.put("shopSelfSupport","true");
        shopbase.put("shopCreateTime",new Date());
        shopbase.put("shopStatus",3);
        shopbase.put("shopTel",String.valueOf(param.get("userMobile")));
        shopbase.put("shopPayment",1);
        shopbase.put("shopType",1);
        shopbase.put("districtId",String.valueOf(param.get("shopArea")));
        shopbase.put("shopInvoices",1);
        shopbase.put("shopIssueInvoice",2);
        shopbase.put("treasureJoinDate",new Date());
        shopbase.put("invoiceSwitchStatus",1);
        shopbase.put("invoiceAuditStatus",1);
        shopbase.put("invoiceSwitchCreateTime",new Date());
        shopbase.put("invoiceSwitchUpdateTime",new Date());
        shopbase.put("shopOperatorTime",new Date());
        Integer torf2 = shopBaseMapper.insertShopBase(shopbase);
        String shopId = String.valueOf(shopbase.get("shopId"));

        ApplyPayOnDeliveryRecordDTO applyPayOnDeliveryRecordDTO = new ApplyPayOnDeliveryRecordDTO();
        //开启货到付款
        applyPayOnDeliveryRecordDTO.setShopId(Integer.valueOf(shopId));
        applyPayOnDeliveryRecordDTO.setUserId(userId);
        applyPayOnDeliveryRecordDTO.setApplyStatus(2);
        applyPayOnDeliveryRecordDTO.setReason("默认开启");
        applyPayOnDeliveryRecordDTO.setShopName(String.valueOf(param.get("shopName")));
        shopCashOnDeliveryMapper.insertApplyPayOnDeliveryRecord(applyPayOnDeliveryRecordDTO);

        //向join_pay表插入数据
        Map<String, Object> joinPay = new HashMap<>();
        joinPay.put("contactPhone",param.get("userMobile"));
        joinPay.put("shopName",param.get("shopName"));
        joinPay.put("shopPay",0);
        joinPay.put("createTime",new Date());
        joinPay.put("auditStatus",3);
        joinPay.put("userId",userId);
        Integer torf4 = shopJoinPayMapper.insertShopJoinPay(joinPay);

        //向udb_ucenter_seller_base插入数据
        Map<String, Object> sellerBase = new HashMap<>();
        sellerBase.put("shopId",shopId);
        sellerBase.put("userId",userId);
        sellerBase.put("sellerName",param.get("userMobile"));
        sellerBase.put("sellerIsAdmin",1);
        sellerBase.put("rightsGroupId",1);
        sellerBase.put("sellerGroupId",1);
        sellerBase.put("shopType",1);
        sellerBase.put("sellerLoginTime",new Date());
        shopBaseMapper.insertSellerbase(sellerBase);

        if (torf2 > 0 && torf4 > 0){
            return true;
        }else{
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();// 回滚
            return false;
        }
    }

    @Override
    public ResponseResult supplierselfshopadd(Map<String, Object> param) throws IOException {
        if (StringUtils.isEmpty(param.get("userMobile").toString())  || StringUtils.isEmpty(param.get("shopName").toString()) ||
                StringUtils.isEmpty(param.get("shopProvince").toString()) || StringUtils.isEmpty(param.get("shopCity").toString()) || StringUtils.isEmpty(param.get("shopArea").toString())){
            return ResponseResult.fail(BizCodeEnume.MISSING_PARAMETER);
        }

        String userInfoStr = RedisUtil.get(YFConfig.YF_PLATFORM_TOKEN_USER + param.get("token"));

        if (null == userInfoStr || userInfoStr.equals("")) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }

        ResponseResult resultResp = usermsServiceClient.checkPhone(param);
        Map data = (Map) resultResp.getData();
        String start = String.valueOf(data.get("start"));
        Boolean selfShop = false;
        //已注册无店铺  要有验证码判断
        if (start.equals("1")){
            String phoneCode = String.valueOf(param.get("phoneCode"));
            String sessionPhoneCode = RedisUtil.get(String.valueOf(param.get("userMobile")));

            if (sessionPhoneCode == null || sessionPhoneCode == ""){
                return ResponseResult.fail(BizCodeEnume.VERIFICATION_CODE_CANNOT_BE_EMPTY);
            }
            if (!phoneCode.equals(sessionPhoneCode)) {
                return ResponseResult.fail(BizCodeEnume.INCORRECT_VERIFICATION_CODE);
            }
            //短信校验后就删除
            RedisUtil.remove(String.valueOf(param.get("userMobile")));
            //新增自营店铺
            selfShop = suppliercreateSelfShop(param);
            if (selfShop){
                Map<String, Object> pwd = new HashMap<>();

                pwd.put("userMobile",param.get("userMobile"));
                if (param.get("password") != null && param.get("password") != "") {
                    pwd.put("password", PasswordUtils.BCryptPasswordEncoder(param.get("password").toString()));
                    Integer integer = this.baseMapper.forgotPassword(pwd);
                }
            }
        } else if(start.equals("5")){
            //用户未注册
            HashMap<String, String> map = new HashMap<>();
            map.put("platForm","1");//客户来源
            map.put("userMobile",String.valueOf(param.get("userMobile")));
            map.put("phoneCode",String.valueOf(param.get("phoneCode")));
            map.put("password",String.valueOf(param.get("password")));
            ResponseResult register = usermsServiceClient.register(map);
            Map userData = (Map) resultResp.getData();
            //用户注册成功开始创建店铺
            if (register.getCode()==BizCodeEnume.REGISTRATION_SUCCESS.getCode()){
                //新增自营店铺
                selfShop = suppliercreateSelfShop(param);
            }else{
                return register;
            }
        }
        if (selfShop){

            return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
        }else{

            return ResponseResult.success(BizCodeEnume.OPERATION_FAILED);
        }
    }

    @Override
    public ResponseResult deleteselfshop(Map<String, Object> paraMap) {
        String token = String.valueOf(paraMap.get("token"));
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_PLATFORM_TOKEN_USER + token);
        if (isExistToken) {
            Integer shopOrder = this.baseMapper.selectShopOrder((Integer) paraMap.get("shopId"));
            if (shopOrder > 0){
                return ResponseResult.fail(BizCodeEnume.UNFINISHED_ORDERS_UNDER_THE_STORE);
            }
            //删除店铺信息
            shopBaseMapper.deleteShopBase((Integer) paraMap.get("shopId"));
            //删除商品信息
            shopBaseMapper.deleteShopJoinBase(paraMap.get("userId").toString());

            return ResponseResult.success(BizCodeEnume.DELETE_SUCCESS);
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
    }

    @Override
    public ResponseResult shopCount(Map<String, Object> map) {
        String token = (String) map.get("token");
        UserInfoVO info = ParseTokenUtils.getPlatformUser(token);
        if (info != null) {
            try {
                Integer type = (Integer) map.get("type");// 类型:1、全部，2、当日，3、本周，4、本月，5、年度
                Integer shopCount = 0;
                if (type == 1) {
                    shopCount = this.baseMapper.queryAllShopCount();
                } else if (type == 2) {
                    shopCount = this.baseMapper.queryTodayShopCount();
                } else if (type == 3) {
                    shopCount = this.baseMapper.queryWeekShopCount();
                } else if (type == 4) {
                    shopCount = this.baseMapper.queryMonthShopCount();
                } else {
                    shopCount = this.baseMapper.queryYearShopCount();
                }
                return ResponseResult.success(shopCount);
            } catch (Exception e) {
                return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
    }

    @Override
    public ResponseResult sentInventoryWarningPort(Map<String, String> param) {

        String orderSellerContact = this.baseMapper.selectById(Integer.valueOf(param.get("shopId"))).getShopTel();

        if (null == orderSellerContact || "".equals(orderSellerContact)) {
            return ResponseResult.fail(BizCodeEnume.MOBILE_NUMBER_IS_EMPTY);
        }
        try {
            String text = "【"+param.get("commonName")+"】";
            Map<String,String> map = new HashMap<>();
            map.put("userMobile",orderSellerContact);
            map.put("text",text);
            thirdPartyServiceClient.sendDuanxin(map);
        } catch (Exception e) {
            return ResponseResult.fail(e.getMessage());
        }

        return ResponseResult.success();
    }

    //插入供应商店铺信息
    @Transactional
    public Boolean suppliercreateSelfShop(Map<String, Object> param){
        String userId = shopBaseMapper.queryUserInfoUserId(String.valueOf(param.get("userMobile")));

        //向shopjoinbase表插入数据
        //获取joinId
        Map<String, Object> joinbase = new HashMap<>();
        Date currentDate = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
        String joinId = SnowflakeIdWorker.getSnowId();
        joinbase.put("joinId",joinId);
        joinbase.put("contactPhone",String.valueOf(param.get("userMobile")));
        joinbase.put("shopName",String.valueOf(param.get("shopName")));
        joinbase.put("shopProvince",String.valueOf(param.get("shopProvince")));
        joinbase.put("shopCity",String.valueOf(param.get("shopCity")));
        joinbase.put("shopArea",String.valueOf(param.get("shopArea")));
        joinbase.put("auditStatus",1);
        joinbase.put("userId",userId);
        joinbase.put("shopType",2);
        joinbase.put("createTime",new Date());
        joinbase.put("lastUpdateTime",new Date());
        joinBaseMapper.insertShopJoinBase(joinbase);

        //向shopbase表插入数据
        Map<String, Object> shopbase = new HashMap<>();
        shopbase.put("userId",userId);
        shopbase.put("shopName",String.valueOf(param.get("shopName")));
        shopbase.put("userName",String.valueOf(param.get("userMobile")));
        shopbase.put("shopClassId",0);
        shopbase.put("shopSelfSupport","true");
        shopbase.put("shopCreateTime",new Date());
        shopbase.put("shopStatus",3);
        shopbase.put("shopBusiness",3);
        shopbase.put("shopType",2);
        shopbase.put("shopTel",String.valueOf(param.get("userMobile")));
        shopbase.put("shopPayment",1);
        shopbase.put("districtId",String.valueOf(param.get("shopArea")));
        shopbase.put("shopInvoices",1);
        shopbase.put("shopIssueInvoice",2);
        shopbase.put("treasureJoinDate",new Date());
        shopbase.put("invoiceSwitchStatus",1);
        shopbase.put("invoiceAuditStatus",1);
        shopbase.put("invoiceSwitchCreateTime",new Date());
        shopbase.put("invoiceSwitchUpdateTime",new Date());
        shopbase.put("shopOperatorTime",new Date());
        Integer torf2 = shopBaseMapper.insertShopBase(shopbase);
        String shopId = String.valueOf(shopbase.get("shopId"));

        ApplyPayOnDeliveryRecordDTO applyPayOnDeliveryRecordDTO = new ApplyPayOnDeliveryRecordDTO();
        //开启货到付款
        applyPayOnDeliveryRecordDTO.setShopId(Integer.valueOf(shopId));
        applyPayOnDeliveryRecordDTO.setUserId(userId);
        applyPayOnDeliveryRecordDTO.setApplyStatus(2);
        applyPayOnDeliveryRecordDTO.setReason("默认开启");
        applyPayOnDeliveryRecordDTO.setShopName(String.valueOf(param.get("shopName")));
        shopCashOnDeliveryMapper.insertApplyPayOnDeliveryRecord(applyPayOnDeliveryRecordDTO);

        //向join_pay表插入数据
        Map<String, Object> joinPay = new HashMap<>();
        joinPay.put("contactPhone",param.get("userMobile"));
        joinPay.put("shopName",param.get("shopName"));
        joinPay.put("shopPay",0);
        joinPay.put("createTime",new Date());
        joinPay.put("auditStatus",3);
        joinPay.put("userId",userId);
        Integer torf4 = shopJoinPayMapper.insertShopJoinPay(joinPay);

        //向udb_ucenter_seller_base插入数据
        Map<String, Object> sellerBase = new HashMap<>();
        sellerBase.put("shopId",shopId);
        sellerBase.put("userId",userId);
        sellerBase.put("sellerName",param.get("userMobile"));
        sellerBase.put("sellerIsAdmin",1);
        sellerBase.put("rightsGroupId",1);
        sellerBase.put("sellerGroupId",1);
        sellerBase.put("shopType",2);
        sellerBase.put("sellerLoginTime",new Date());
        shopBaseMapper.insertSellerbase(sellerBase);

        if (torf2 > 0 && torf4 > 0){
            return true;
        }else{
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();// 回滚
            return false;
        }
    }

    @Override
    public String selectShopNameByShopId(Integer shopId) {
        return shopBaseMapper.selectShopNameByShopId(shopId);
    }

    @Override
    public ResponseResult updateFreeShipping(ManageShopFreeShippingDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_SHOP_SETSHOP, param.getToken());

        if (userPermissionsResult.getFlag()) {
            Integer shopId = Integer.valueOf(userPermissionsResult.getShopId());
            param.setShopId(shopId);
            shopBaseMapper.updateFreeShipping(param);
        } else {
            return ResponseResult.fail(CommonStatusEnum.FAIL.getCode(),BizCodeEnume.INSUFFICIENT_PERMISSIONS.getMsg());
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryAllshop(Map<String, Object> map) {
        IPage<ShopBaseEntity> page=this.baseMapper.selectshop(new Query<ShopBaseEntity>().getPage(map), map);

        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult querySelfShopDetail(Integer shopId) {
        // 查询详情
        SelfShopDetailVO result = this.baseMapper.selectSelfShopDetail(shopId);

        // 获取店铺地址
        String shopAddress = getAddress(String.valueOf(result.getShopProvince()),String.valueOf(result.getShopCity()),String.valueOf(result.getShopArea()));
        result.setShopAddress(shopAddress);

        return ResponseResult.success(result);
    }

    @Override
    public ResponseResult updateSelfShop(SelfShopUpdateDTO dto) {
        // 下架该店铺商品
        if (dto.getShopStatus().equals(0)) {
            Integer shopOrder = this.baseMapper.selectShopOrder(dto.getShopId());
            if (shopOrder > 0){
                return ResponseResult.fail(BizCodeEnume.UNFINISHED_ORDERS_UNDER_THE_STORE);
            }
            CommonShopStateDTO commonParam = new CommonShopStateDTO();
            commonParam.setShopId(dto.getShopId());
            commonParam.setShopStatus(dto.getShopStatus());
            commonParam.setGoodsIsShelves(3);
            commonParam.setCommonState(2);
            this.baseMapper.updateShopState(commonParam);
            this.baseMapper.updateGoodsState(commonParam);
        }
        if (dto.getShopStatus().equals(3)) {
            this.baseMapper.updateShopState1(dto.getShopId());
        }
        dto.setDistrictId(dto.getShopArea());
        this.baseMapper.updateSelfShop(dto);
        this.baseMapper.updateSelfShopJoin(dto);

        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult querySelfShopList(ShopBaseListQueryDTO dto) throws IllegalAccessException {

        Map data= ParseMapUtils.beanToMap(dto);
        IPage<SelfShopListQueryVO> page=this.baseMapper.selectSelfShopList(new Query<SelfShopListQueryVO>().getPage(data),
                dto);
        for(SelfShopListQueryVO shop :page.getRecords()){
            String shopLocation = getAddress(shop.getShopProvince()+"",shop.getShopCity()+"",shop.getShopArea()+"");
            shop.setShopLocation(shopLocation);
        }

        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult querySetShop(UserTokenBeanDTO param) {
        ManageSetShopParamQueryDTO result = new ManageSetShopParamQueryDTO();
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(null, param.getToken());
        if (!userPermissionsResult.getFlag()) {
            return ResponseResult.fail(10086, "没有权限");
        }
        // 根据code存储用户信息
        String userInfoStr = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + param.getToken());
        UserInfoDTO dto = JSON.parseObject(userInfoStr, UserInfoDTO.class);
        UserInfoVO userInfo = dto.getUser();
        if (null == userInfo.getSellerIsAdmin() && null != userInfo.getShopGateId()) {
            //设置门店
            ShopGateDTO shopGate = this.baseMapper.queryShopGateById2(userInfo.getShopGateId());
            result.setShopId(shopGate.getShopId());
            result.setShopName(shopGate.getGatestoreName());
            //1是门店
            result.setIsGateShop(1);
            return ResponseResult.success(result);
        }
        // 设置店铺
        result = this.baseMapper.selectSetShop(userPermissionsResult.getShopId());
        //2是店铺
        result.setIsGateShop(2);
        return ResponseResult.success(result);
    }

    @Override
    @Transactional
    public ResponseResult updateSetShop(ManageSetShopParamAddDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_SHOP_SETSHOP, param.getToken());

        if (!userPermissionsResult.getFlag()) {
            return ResponseResult.fail(10086, "没有权限");
        }
        List<ShopBaseEntity> entity=this.baseMapper.selectList(new LambdaQueryWrapper<ShopBaseEntity>()
                .eq(ShopBaseEntity::getShopName,param.getShopName()));
        if(!CollectionUtils.isEmpty(entity) && param.getUpdateShopName() != null && param.getUpdateShopName()) {
            return ResponseResult.fail(BizCodeEnume.DUPLICATE_STORE_NAME);
        }
        param.setShopId(userPermissionsResult.getShopId());
        param.setUserId(userPermissionsResult.getUserId());
        ManageSetShopParamQueryDTO shopMes = shopBaseMapper.selectSetShop(userPermissionsResult.getShopId());
        if (!shopMes.getShopName().equals(param.getShopName())) {
            param.setShopNameVerify(2);
            param.setNewShopName(param.getShopName());
            param.setShopName(shopMes.getShopName());
        }
        // 设置店铺
        param.setUpdateTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
        shopBaseMapper.updateSetShop(param);
        // shopBaseMapper.updateContactsPhone(param);
        //更新配置
        Map<String, Object> logo = new HashMap<>();
        if (param.getWapLoginLogo() != null && param.getWapLoginLogo() != ""){

            logo.put("configKey","logo_copywriting_ico_h5_registr_" + userPermissionsResult.getShopId());
            logo.put("configValue",param.getWapLoginLogo());
            //update
            Integer updateNav = this.baseMapper.updateByPrimaryConfigKey(logo);
            RedisUtil.remove("SYSTEM_logo_copywriting");
            RedisUtil.remove("SYSTEM_" + logo.get("configKey").toString());
        }
        if (param.getRegistrationPage() != null ){
            logo.put("configKey","registration_page_" + userPermissionsResult.getShopId());

            String fromBase64 = null;
            try {
                String data = String.valueOf(param.getRegistrationPage());
                fromBase64 = Base64Utils.getFromBase64(data);

            } catch (Exception e) {
                e.printStackTrace();
                return ResponseResult.fail(0, "解码失败");
            }
            logo.put("configValue",fromBase64);
            //update
            Integer updateNav = shopBaseMapper.updateByPrimaryConfigKey(logo);
            RedisUtil.remove("SYSTEM_logo_copywriting");
            RedisUtil.remove("SYSTEM_" + logo.get("configKey").toString());
        }
        if (param.getRegistrationUser() != null ){
            logo.put("configKey","registration_user_" + userPermissionsResult.getShopId());

            String fromBase64 = null;
            try {
                String data = String.valueOf(param.getRegistrationUser());
                fromBase64 = Base64Utils.getFromBase64(data);

            } catch (Exception e) {
                e.printStackTrace();
                return ResponseResult.fail(0, "解码失败");
            }
            logo.put("configValue",fromBase64);
            //update
            Integer updateNav = shopBaseMapper.updateByPrimaryConfigKey(logo);
            RedisUtil.remove("SYSTEM_logo_copywriting");
            RedisUtil.remove("SYSTEM_" + logo.get("configKey").toString());
        }
		return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult addShopSlide(ManageShopSlideDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_SHOP_SETSHOP, param.getToken());

        if (!userPermissionsResult.getFlag()) {
            return ResponseResult.fail(10086, "没有权限");
        }
        param.setShopId(userPermissionsResult.getShopId());

        if (null != param.getType() && param.getType().equals(2)) {
            shopBaseMapper.updateMobileShopSlide(param);
        } else {
            shopBaseMapper.updateShopSlide(param);
        }
        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryShopSlide(ManageShopSlideDTO param) {
        ManageShopSlideVO shopSlides = null;
        UserInfoVO userInfoVO = ParseTokenUtils.getUserInfoByToken(param.getToken());
        if (userInfoVO == null) {
            return ResponseResult.fail(10086, "没有权限");
        }
        String str = ",,,,";
        String[] split = str.split(",", -1);
        //
        shopSlides = shopBaseMapper.selectShopSlide(userInfoVO.getShopId());
        if (shopSlides == null || shopSlides.equals("")) {
            shopSlides = new ManageShopSlideVO();
            shopSlides.setShopSlide(null);
            shopSlides.setShopSlideList(new ArrayList<String>());
            shopSlides.setShopSlideurl(null);
            shopSlides.setShopSlideurlList(new ArrayList<String>());
            return ResponseResult.success(1,"轮播信息为空", shopSlides);
        }
        String shopSlide = shopSlides.getMobileShopSlide();
        shopSlides.setMobileShopSlide(null);
        String shopSlideUrl = null;
        if (null != param.getType() && param.getType().equals(2)) {
            shopSlideUrl = shopSlides.getMobileShopSlideurl();
            shopSlides.setMobileShopSlideurl(null);
        } else {
            shopSlide = shopSlides.getShopSlide();
            shopSlideUrl = shopSlides.getShopSlideurl();
        }

        if (shopSlide != null && !"".equals(shopSlide)) {
            String[] shopSlideArr = shopSlide.split(",");
            shopSlides.setShopSlideList(Arrays.asList(shopSlideArr));
        } else {
            shopSlides.setShopSlideList(Arrays.asList(split));
        }

        if (shopSlideUrl != null && !"".equals(shopSlideUrl)) {
            String[] shopSlideUrlArr = shopSlideUrl.split(",");
            shopSlides.setShopSlideurlList(Arrays.asList(shopSlideUrlArr));
        } else {
            shopSlides.setShopSlideurlList(Arrays.asList(split));
        }
        return ResponseResult.success(shopSlides != null ? shopSlides : new ArrayList<String>());
    }

    @Override
    public ResponseResult queryDeposit(DepositDetailDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_SHOP_SETSHOP, param.getToken());
        if (!userPermissionsResult.getFlag()) {
            return ResponseResult.fail(10086, "没有权限");
        }
        DepositDetailVO result = shopBaseMapper.selectDeposit(userPermissionsResult.getShopId());
        return ResponseResult.success(result);

    }

    @Override
    public ResponseResult updateDeposit(DepositDetailDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_SHOP_SETSHOP, param.getToken());

        if (!userPermissionsResult.getFlag()) {
            return ResponseResult.fail(10086, "没有权限");
        }
        // 1:已缴纳2:尚未缴纳3审核中4审核失败
        param.setDepositStatus(3);
        param.setShopId(userPermissionsResult.getShopId());
        shopBaseMapper.updateManageDeposit(param);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryReturnBond(DepositDetailDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_SHOP_SETSHOP, param.getToken());

        if (!userPermissionsResult.getFlag()) {
            return ResponseResult.fail(10086, "没有权限");
        }
        ReturnBondVO result = shopBaseMapper.selectReturnBond(userPermissionsResult.getShopId());
        return ResponseResult.success(result);

    }

    @Override
    public ResponseResult updateReturnBond(ReturnBondDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_SHOP_SETSHOP, param.getToken());
        if (!userPermissionsResult.getFlag()) {
            return ResponseResult.fail(10086, "没有权限");
        }
        param.setShopId(userPermissionsResult.getShopId());
        param.setReturnBondStatus(3);
        param.setUpdateTime(new Date());
        shopBaseMapper.updateReturnBond(param);
        return ResponseResult.success();

    }

    @Override
    public ResponseResult updateInvoiceSwitch(Map<String, Object> param) {
        String token = (String) param.get("token");
        // 根据code存储用户信息
        String userInfoStr = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + token);
        UserInfoDTO dto = JSON.parseObject(userInfoStr, UserInfoDTO.class);
        UserInfoVO userInfo = dto.getUser();
        if (null == userInfo.getShopId()) {
            return ResponseResult.fail(10086, "没有权限");
        }
        param.put("userId", userInfo.getUserId());
        try {
            Integer shopId = shopBaseMapper.getShopId(param);
            param.put("shopId", shopId);

            int invoiceSwitchStatus = (Integer) param.get("invoiceSwitchStatus");
            // invoiceSwitchStatus= 1 则是开启，invoiceSwitchStatus = 0 则是关闭
            //如果关闭开票功能，需要对未走完流程的开票订单做判断
            if (0 == invoiceSwitchStatus) {
                Integer undealedOrderCount = shopBaseMapper.getUndealedOrderCount(param);
                if (undealedOrderCount > 0) {
                    return ResponseResult.fail(2, "由于当前有未完成开票的订单，暂时无法关闭，请至订单页面查看订单进度");
                }
            }
            shopBaseMapper.updateInvoiceSwitch(param);
            return ResponseResult.success();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseResult.fail(2,"操作异常");
        }
    }

    @Override
    public ResponseResult queryInvoiceSwitch(Map<String, Object> param) {
        String token = (String) param.get("token");
        // 根据code存储用户信息
        String userInfoStr = RedisUtil.get(YFConfig.YF_USER_TOKEN_USER + token);
        UserInfoDTO dto = JSON.parseObject(userInfoStr, UserInfoDTO.class);
        UserInfoVO userInfo = dto.getUser();
        if (null == userInfo.getShopId()) {
            return ResponseResult.fail(10086, "没有权限");
        }
        param.put("userId", userInfo.getUserId());
        try {
            Integer shopId = shopBaseMapper.getShopId(param);
            param.put("shopId", shopId);
            InvoiceSwitchEntityVO resp = shopBaseMapper.queryShopInvoiceSwitch(param);
            return ResponseResult.success(resp);
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseResult.fail(2,"操作异常");
        }
    }

    @Override
    public ResponseResult queryShopJoinAptitudeDetailForPlatform(Map<String, Object> param) {
        UserInfoVO userInfoVO = ParseTokenUtils.getPlatformUser(param.get("token").toString());
        if (userInfoVO==null) {
            return ResponseResult.fail(BizCodeEnume.USER_DOES_NOT_EXIST);
        }
        //查找店铺资质详情
        ShopJoinAptitudeInfoForPlatformDetailVO data = this.baseMapper.queryShopJoinAptitudeDetailForPlatform(param);
        ResponseResult blLocation = baseServiceClient.getAddressString(data.getBlProvince(), data.getBlCity(), data.getBlArea());
        data.setBlLocation(String.valueOf(blLocation.getData()));
        return ResponseResult.success(data);
    }

    @Override
    public ResponseResult verifyShopMesModify(ShopBusinessModifyVerifyDTO param) {

        ShopMessageLogEntity detail = shopMessageLogMapper.selectOne(new LambdaQueryWrapper<ShopMessageLogEntity>()
                                     .eq(ShopMessageLogEntity::getShopId,param.getShopId()));
        //shopCompanyMapper.updateShopBusiness(detail);
        detail.setShopVerifyStatus(param.getShopVerifyStatus());
        detail.setShopVerifyRemark(param.getShopVerifyRemark());
        this.baseMapper.verifyShopMesModify(param);
        shopMessageLogMapper.updateById(detail);

        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult queryShopJoinAptitudeListForPlatform(Map<String, Object> param) {
        UserInfoVO userInfoVO = ParseTokenUtils.getPlatformUser(param.get("token").toString());
        if (userInfoVO==null) {
            return ResponseResult.fail(BizCodeEnume.USER_DOES_NOT_EXIST);
        }
        //设置分页 查找分页的店铺资质审核列表
        Page<ShopJoinAptitudeInfoForPlatformVO> page = new Page<>((Integer) param.get("page"), (Integer) param.get("limit"));
        IPage<ShopJoinAptitudeInfoForPlatformVO> result = this.baseMapper.queryShopJoinAptitudeListForPlatform(page, param);
        return ResponseResult.success(PageUtils.getPage(result));
    }

    @Override
    public ResponseResult verifyShopNameModify(ShopNameModifyVerifyDTO param) {
        //审核详情
        param.setShopNameRemark(null == param.getShopNameRemark() ? "" : param.getShopNameRemark());
        //审批参数设置
        LambdaUpdateWrapper<ShopBaseEntity> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(ShopBaseEntity::getShopNameVerify, param.getShopNameVerify());
        updateWrapper.set(ShopBaseEntity::getShopNameRemark, param.getShopNameRemark());
        //审核通过
        if (param.getShopNameVerify().equals(CommonType.isApproved.APPROVED.getCode())) {
            Map<String, Object> map = new HashMap<>();
            map.put("shopName", param.getNewShopName());
            map.put("shopId", param.getShopId());
            updateWrapper.set(ShopBaseEntity::getShopName, param.getNewShopName());
            updateWrapper.set(ShopBaseEntity::getNewShopName, param.getShopName());
            goodsServiceClient.updateGoodsCommonByMap(map);
            goodsServiceClient.updateGoodsBaseByMap(map);
            orderServiceClient.updateOrderUserCarByMap(map);
            orderServiceClient.updateOrderBaseByMap(map);
            orderServiceClient.updateOrderSettlementByMap(map);
            //修改经销信息表
            baseServiceClient.updateDealerApplyInfotByMap(map);

        }
        updateWrapper.eq(ShopBaseEntity::getShopId, param.getShopId());
        this.update(updateWrapper);
        return ResponseResult.success(BizCodeEnume.UPDATE_SUCCEEDED);
    }

    @Override
    public ResponseResult queryShopNameModifyList(ShopBaseListDTO param) {
        //分页查询
        Page<ShopNameModifyListVO> page = new Page<>(param.getPage(), param.getLimit());
        IPage<ShopNameModifyListVO> shopList = this.baseMapper.selectShopNameModifyList(page, param);
        return ResponseResult.success(PageUtils.getPage(shopList));
    }

    @Override
    public ResponseResult queryShopListExp(ShopBaseListDTO param) {
        ResponseResult rr = getShopSetParameter(param);
        if (rr.getCode() != CommonStatusEnum.SUCCESS.getCode()) {
            return rr;
        }
        //查询店铺设置
        List<ShopBaseListExpVO> shopList = this.baseMapper.selectByShopListExp(param);
        String[] headers = {"店铺ID", "店铺联系人", "联系人电话", "店铺名称", "店铺类型", "店铺分类", "所在区域",
                "详细地址", "入驻时间", "状态"};
        List<Map<String, String>> list = Lists.newArrayList();
        SimpleDateFormat sim2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (ShopBaseListExpVO res : shopList) {
            String format = sim2.format(res.getShopCreateTime());
            res.setShopCreateTimes(format);
            HashMap<String, String> map = Maps.newHashMap();
            if (res.getShopStatus() != null) {
                switch (res.getShopStatus() + "") {
                    default:
                    case "0":
                        res.setShopStatus(CommonType.storeStatus.CLOSE.getDesc());
                        break;
                    case "1":
                        res.setShopStatus(CommonType.storeStatus.REVIEWED_DATA.getDesc());
                        break;
                    case "2":
                        res.setShopStatus(CommonType.storeStatus.REVIEWED_PAYMENT.getDesc());
                        break;
                    case "3":
                        res.setShopStatus(CommonType.storeStatus.SUCCESSFULLY.getDesc());
                        break;
                }
            }
            if (res.getShopType() != null) {
                switch (res.getShopType() + "") {
                    case "0":
                        res.setShopType(CommonType.JoinType.PERSONAL_SHOP.getDesc());
                        break;
                    case "1":
                        res.setShopType(CommonType.JoinType.BUSINESS_SHOP.getDesc());
                        break;
                }
            }
            String blLocation = baseServiceClient.getAddressString(res.getShopProvince(), res.getShopCity(), res.getShopArea()).getData().toString();
            map.put("店铺ID", res.getShopId() + "");
            map.put("店铺联系人", res.getContactName());
            map.put("联系人电话", res.getContactPhone());
            map.put("店铺名称", res.getShopName());
            map.put("店铺类型", res.getShopType());
            map.put("店铺分类", res.getShopClassName());
            map.put("所在区域", blLocation);
            map.put("详细地址", res.getShopAddress());
            map.put("入驻时间", res.getShopCreateTimes());
            map.put("状态", res.getShopStatus());
            list.add(map);
        }
        // excel文件名
        Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
         * 该list为每个sheet页的数据
         */> map = Maps.newHashMap();
        map.put("店铺列表", list);
        String url = ExcelsUtil.createExcel(headers, map, new int[]{0}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);
        return ResponseResult.success(url);
    }

    @Override
    public ResponseResult queryShopList(ShopBaseListDTO param) {
        ResponseResult rr = getShopSetParameter(param);
        if (rr.getCode() != CommonStatusEnum.SUCCESS.getCode()) {
            return rr;
        }
        param = JSON.parseObject(JSON.toJSONString(rr.getData()), ShopBaseListDTO.class);
        //设置分页 查询店铺设置
        Page<ShopBaseListVO> page = new Page<>(param.getPage(), param.getLimit());
        IPage<ShopBaseListVO> shopList = this.baseMapper.selectByShopList(page, param);
        List<ShopBaseListVO> list = shopList.getRecords();
        for (ShopBaseListVO shopBaseListVO : list) {
            String address = shopBaseListVO.getShopAddress();
            String completeAddress = baseServiceClient.getAddressString(
                    shopBaseListVO.getShopProvince(), shopBaseListVO.getShopCity(), shopBaseListVO.getShopArea()).getData().toString();
            shopBaseListVO.setShopCompanyAddress(completeAddress);
            shopBaseListVO.setShopLocation(completeAddress);
            shopBaseListVO.setCompanyAddressDetail(address);
            shopBaseListVO.setShopAddress(completeAddress + address + "");
        }
        return ResponseResult.success(PageUtils.getPage(shopList));
    }

    @Override
    public ResponseResult updateShopBase(ShopBaseUpdateDTO param) {
        Map<String, Object> map = new HashMap<>();
        Map<String, Object> shopMap = new HashMap<>();
        Map<String, Object> goodsMap = new HashMap<>();
        List<Integer> commonIds = new ArrayList<>();
        List<Integer> shopIds = Collections.singletonList(param.getShopId());
        //得到用户信息进行判断
        UserInfoVO ui = ParseTokenUtils.getPlatformUser(param.getToken());
        if (ui == null) {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        param.setShopSelfSupport(CommonType.booleanStatus.FALSE.getDesc());
        param.setShopOperatorTime(DateUtils.getTime());
        map.put("shopId", param.getShopId());
        ShopBaseEntity shopBase = this.baseMapper.selectOne(new LambdaQueryWrapper<ShopBaseEntity>()
                .eq(ShopBaseEntity::getShopId, param.getShopId()));
        //关闭店铺
        if (param.getShopStatus().equals(CommonType.shopStatus.STORE_CLOSED.getCode())) {

            ResponseResult result = orderServiceClient.updateShopByOrderInfo(map);
            if (result.getCode() == CommonStatusEnum.FAIL.getCode()) {
                //店铺下有订单未完成,不能关闭
                return ResponseResult.fail(BizCodeEnume.UNFINISHED_ORDERS_UNDER_THE_STORE);
            }

            //关闭店铺查询所有要下的商品id
            commonIds = goodsServiceClient.queryCommonIdList(param.getShopId());
            // 1 是添加  2是删除
            shopMap.put("type", CommonType.operateStatus.DEL.getCode());
            goodsMap.put("type", CommonType.operateStatus.DEL.getCode());
            param.setShopOperator("编辑/关闭:" + ui.getUserRealname());
            //下架店铺商品
            CommonShopStateDTO commonParam = new CommonShopStateDTO(param.getShopId(), param.getShopStatus(),
                    CommonType.goodsIsShelves.STORE_OFF_SHELF.getCode(), CommonType.commonSpuState.STORE_OFF_SHELF.getCode());
            goodsServiceClient.updateCommonState(commonParam);
            goodsServiceClient.updateGoodsState(commonParam);
            //失效店铺代金券
            Map<String, Object> vmap = new HashMap<>();
            vmap.put("shopId", param.getShopId());
            this.baseMapper.updateVoucherState(vmap);
            this.baseMapper.updateVoucherBaseState(vmap);
            //删除收藏店铺
            usermsServiceClient.delFavoritesByShopId(param.getShopId());
            //更改店铺拥有人状态
            //usermsServiceClient.updateUserIsShop(shopBase.getUserId(), shopBase.getShopId(), CommonType.commonStatus.NO.getCode());

            //开启店铺
        } else if (param.getShopStatus().equals(CommonType.shopStatus.STORE_OPEN_SUCCESS.getCode())) {
            // 1 是添加  2是删除
            shopMap.put("type", CommonType.operateStatus.ADD.getCode());
            goodsMap.put("type", CommonType.operateStatus.DEL.getCode());
            param.setShopOperator("编辑/开启:" + ui.getUserRealname());
            //更改店铺拥有人状态
            //usermsServiceClient.updateUserIsShop(shopBase.getUserId(), shopBase.getShopId(), CommonType.commonStatus.YES.getCode());
        }
        // 是否更改店铺名
        if (!shopBase.getShopName().equals(param.getShopName())) {
            map.put("shopName", param.getShopName());
            goodsServiceClient.updateGoodsBaseByMap(map);
            goodsServiceClient.updateGoodsCommonByMap(map);
        }
        this.baseMapper.updateShopBaseStatus(param);
        shopMap.put("shopIds", shopIds);
        goodsMap.put("commonIdS", commonIds);
        //更新店铺信息
        //MqSendUtils.mqSendShop(map);
        //更新商品信息
        MqSendUtils.mqSendGoods(map);
        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryUpdateShopBase(Map<String, Object> param) {
        ShopBaseVO result = this.baseMapper.selectInfoByShopId(Integer.valueOf(param.get("shopId").toString()));
        return ResponseResult.success(result);
    }

    @Override
    public ResponseResult auditShopInvoiceSwitch(Map<String, Object> param) {
        //map转对象
        ShopBaseEntity shopBase = ParseMapUtils.parseMap2Object(param, ShopBaseEntity.class);
        //设置更新条件
        LambdaUpdateWrapper<ShopBaseEntity> updateWrapper = new LambdaUpdateWrapper<>();
        if (!"".equals(shopBase.getPlatformComment())) {
            updateWrapper.set(ShopBaseEntity::getPlatformComment, shopBase.getPlatformComment());
        }
        updateWrapper.set(ShopBaseEntity::getInvoiceAuditStatus, shopBase.getInvoiceAuditStatus());
        updateWrapper.set(ShopBaseEntity::getInvoiceSwitchUpdateTime, DateUtils.getTime());
        updateWrapper.eq(ShopBaseEntity::getShopId, shopBase.getShopId());
        //更新
        try {
            this.update(updateWrapper);
            return ResponseResult.success();
        } catch (Exception e) {
            log.error(e.getMessage());
            return ResponseResult.fail();
        }
    }

    @Override
    public ResponseResult queryShopInvoiceSwitchs(ShopBaseListDTO param) {
        //设置分页
        Page<ShopBaseEntity> page = new Page<>(param.getPage(), param.getLimit());
        IPage<ShopBaseEntity> result = this.baseMapper.queryShopInvoiceSwitchs(page, param);
        return ResponseResult.success(PageUtils.getPage(result));
    }

    private ResponseResult getShopSetParameter(ShopBaseListDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        if (userInfo== null) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        String userId = userInfo.getUserId();
        List<Integer> districtChildIdList = null;
        //fegin调用查找
        if (!userInfo.getRightsGroupId().equals(1)) {
            ResponseResult districtChildIds = usermsServiceClient.getDistrictChildIds(userId);
            if (null != districtChildIds) {
                districtChildIdList = JSON.parseArray(JSON.toJSONString(districtChildIds.getData()), Integer.class);
            }
        }
        param.setDistrictChildIdList(districtChildIdList);
        return ResponseResult.success(param);
    }


    private String getAddress(String provinceId, String cityId, String districtId) {
        if ((provinceId == null || provinceId.equals("")|| provinceId.equals("null"))
                && (cityId == null || cityId.equals("") || cityId.equals("null"))
                && (districtId == null || districtId.equals("") || districtId.equals("null"))) {
            return "";
        }
        String provinceName = baseServiceClient.queryProvinceport(provinceId);
        String cityName = baseServiceClient.queryProvinceport(cityId);
        String districtName = baseServiceClient.queryProvinceport(districtId);
        return provinceName + cityName + districtName;
    }

    @Override
    public ResponseResult shopTodayNumber(Map<String, Object> map) {
        String token = (String) map.get("token");
        UserInfoVO info = ParseTokenUtils.getPlatformUser(token);
        if (info != null) {
            try {
                Integer shopCount = this.baseMapper.queryTodayShopCount();
                return ResponseResult.success(shopCount);
            } catch (Exception e) {
                return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
            }
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID.getCode(),BizCodeEnume.TOKEN_IS_INVALID.getMsg());
        }
    }

    @Override
    public ResponseResult uniappQueryShopList(ShopListQueryDTO param) {
        try {
            //将对象转换为map
            Map data = ParseMapUtils.beanToMap(param);
            //分页查询数据
            IPage<ShopListQueryResultVO> page = this.baseMapper.selectUniappQueryShopList(new Query<ShopListQueryResultVO>().getPage(data),param);
            List<ShopListQueryResultVO> records = page.getRecords();
            for (ShopListQueryResultVO record : records) {
                if(null == record.getShopLogo()){
                    String configValue = baseServiceClient.selectConfigValueFeign("logo_copywriting_ico_shop");
                    record.setShopLogo(configValue);
                }
                List<Map<String, Object>> maps = this.baseMapper.selectUniappQueryShopGoods(record);
                record.setGoods(maps);
            }
            page.setRecords(records);
            return ResponseResult.success(PageUtils.getPage(page));
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR.getCode(),BizCodeEnume.SYSTEM_ERROR.getMsg());
    }

    @Override
    public ResponseResult shopGroupingStatistics(Map<String, Object> map) {
        String token = (String) map.get("token");
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_PLATFORM_TOKEN_USER + token);
        if (isExistToken) {
            List<Map<String, Object>> goodsGroupingList =  new ArrayList<>();
            String year = DateUtils.getYear();//获取年
            //循环遍历每月开始时间和结束时间
            for (int i = 1; i <= 12 ; i++) {
                Map<String, Object> shopGroupingStatistics = new HashMap<>();
                //获取当前年 的某月 的开始 结束时间
                Map<String, String> stringStringMap = DateUtils.scheduleTimeNday(Integer.valueOf(year), i);
                Integer num = this.baseMapper.selectCount(new LambdaQueryWrapper<ShopBaseEntity>()
                              .ge(ShopBaseEntity::getShopCreateTime,stringStringMap.get("startTimeStr"))
                              .le(ShopBaseEntity::getShopCreateTime,stringStringMap.get("endTimeStr")));
                shopGroupingStatistics.put("num",num);
                shopGroupingStatistics.put("time",DateUtils.dateGeShiHua(stringStringMap.get("startTimeStr"),"yyyy年MM月"));
                goodsGroupingList.add(shopGroupingStatistics);
            }
           return ResponseResult.success(goodsGroupingList);
        } else {
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }

    }

    @Override
    public ResponseResult addShopDecoration(ShopDecorationAddDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_SHOP_SETSHOP, param.getToken());

        if (userPermissionsResult.getFlag()) {
            param.setShopId(Integer.valueOf(userPermissionsResult.getShopId()));
            this.baseMapper.updateShopDecoration(param);

        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        return ResponseResult.success(BizCodeEnume.OPERATION_SUCCESSFUL);
    }

    @Override
    public ResponseResult queryShopDecoration(UserTokenBeanDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_SHOP_SETSHOP, param.getToken());

        if (userPermissionsResult.getFlag()) {

            ShopBaseEntity entity = shopBaseMapper.selectOne(new LambdaQueryWrapper<ShopBaseEntity>()
                                    .eq(ShopBaseEntity::getShopId,userPermissionsResult.getShopId())
                                    .eq(ShopBaseEntity::getShopStatus,CommonType.shopStatus.STORE_OPEN_SUCCESS.getCode()));
            return ResponseResult.success(entity);
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }

    }

    @Override
    public ResponseResult checkShopIsTreasure(UserTokenBeanDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getUserInfoByToken(param.getToken());

        Boolean flag = false;
        Integer treasureGradeId = this.baseMapper.selectById(userInfo.getShopId()).getTreasureGradeId();

        if (treasureGradeId.intValue() != 0) {
            flag = true;
        }

        return ResponseResult.success(flag);
    }

    @Override
    public ResponseResult queryShopTreasureGrade(UserTokenBeanDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_SHOP_SETSHOP, param.getToken());
        ShopTreasureGradeVO result = null;

        if (userPermissionsResult.getFlag()) {


            result = this.baseMapper.selectShopTreasureGrade(userPermissionsResult.getShopId());
            return ResponseResult.success(result);
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }

    }

    @Override
    public ResponseResult updateShopTreasureGrade(ShopTreasureGradeUpdateDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService
                .judgePermissions(PermissionsConstant.SERLLER_SHOP_SETSHOP, param.getToken());

        if (userPermissionsResult.getFlag()) {
            param.setShopId(userPermissionsResult.getShopId());
            param.setTreasureStatus(CommonType.TreasureStatus.VERIFING.getCode());
            this.baseMapper.updateShopTreasureGrade(param);
        } else {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }

        return ResponseResult.success();
    }

    @Override
    public ResponseResult queryShopListFilter(WebShopListQueryDTO param) throws IllegalAccessException {
        //查询plus状态
        Integer selectplus = this.baseMapper.selectplus();
        param.setCurrentPage((param.getPage() - 1) * param.getLimit());
        Map<String,Object> shopListResult = new HashMap<>();
//        shopListResult.put("selectplus",selectplus);
        Integer districtId = param.getDistrictId();
        if(null  != districtId) {
            // 从缓存中取
            List<ShopAllBaseDistrictVO> allMenu = null;
            String value = RedisUtil.get(Constants.CACHE_DISTRICTS_SHOP_ADDRESS_ALL_BASE);
            if (null != value && !value.equals("")) {
                allMenu = JsonUtils.string2Obj(value, List.class, ShopAllBaseDistrictVO.class);
            } else {
                allMenu = this.baseMapper.selectAllDistrict2();
            }
            // 设置缓存
            RedisUtil.set(Constants.CACHE_DISTRICTS_SHOP_ADDRESS_ALL_BASE, JsonUtils.toString(allMenu), RedisUtil.EXRP_MONTH);

            List<Integer> districtList = getDistrictList3(allMenu, districtId);
            param.setDistrictList(districtList);
        }
        Map data= ParseMapUtils.beanToMap(param);
        IPage<WebShopListQueryResultVO> page=this.baseMapper.selectShopListFilter(new Query<WebShopListQueryResultVO>().getPage(data),
                param);


        if (!CollectionUtils.isEmpty(page.getRecords())) {
            for (WebShopListQueryResultVO shopListQueryResult : page.getRecords()) {
                Integer shopId = shopListQueryResult.getShopId();
                // 获取店铺导航
                List<MerchantShopNavQueryDTO> shopNav = shopNavMapper.selectShopNav(shopId);

                // 获取店铺默认值
                getShopDefaultValue(shopListQueryResult);
                // 查询店铺商品
                List<GdsListQueryResultVO> commonList = this.baseMapper.selectByShopId3(shopId);
                shopListQueryResult.setCommonList(commonList);
                // 查询店铺商品数量
                Integer shopGoodsSum = this.baseMapper.selectShopSum(shopId);
                shopListQueryResult.setShopNav(shopNav);
                shopListQueryResult.setShopGoodsSum(shopGoodsSum);
            }
        }

        try {
            if (null != page.getRecords()) {
                // 获取店铺评分
                page.setRecords(shopEvaluationService.queryShopScore(page.getRecords()));
            }
        } catch (Exception e) {

        }
//        shopListResult.put("page",PageUtils.getPage(page));
        return ResponseResult.success(PageUtils.getPage(page));
    }

    public void getShopDefaultValue(WebShopListQueryResultVO shopListQueryResult) {
        String configValue = null;
        ShopConfigDefaultValueVO shopConfig = null;
        if (null != shopListQueryResult.getShopSlide() && !shopListQueryResult.getShopSlide().equals("")) {
            shopListQueryResult.setShopSlide(shopListQueryResult.getShopSlide().split(",", -1)[0]);
        } else {
            configValue = this.baseMapper.selectConfigValue("logo_copywriting_ico_shop");

            shopListQueryResult.setShopSlide(configValue);
        }

        if (shopListQueryResult.getShopLogo() == null || shopListQueryResult.getShopLogo().equals("")) {
            if (shopConfig == null) {
                configValue = this.baseMapper.selectConfigValue("logo_copywriting_ico_shop");

            }
            shopListQueryResult.setShopLogo(configValue);
        }
    }

    /**
     * 获取商品分类所有的父分类id
     *
     * @param allMenu
     * @param catId
     * @return
     */
    public List<Integer> getDistrictList3(List<ShopAllBaseDistrictVO> allMenu, Integer catId) {
        List<Integer> allChildCatIds = Lists.newArrayList();

        if (!CollectionUtils.isEmpty(allMenu)) {
            for (ShopAllBaseDistrictVO catMenu : allMenu) {
                if (catMenu.getDistrictId().equals(catId)) {
                    allChildCatIds.add(catMenu.getDistrictId());
                    if (!catMenu.getDistrictParentId().equals(0)) {
                        getDistrictChild3(allMenu, catMenu.getDistrictParentId(), allChildCatIds);
                    }
                    break;
                }

            }
        }
        return allChildCatIds;

    }



    /**
     * 找出子菜单
     *
     * @param
     * @param
     * @return
     */
    private List<Integer> getDistrictChild3(List<ShopAllBaseDistrictVO> allMenu, Integer parentId,
                                            List<Integer> allChildCatIds) {

        for (ShopAllBaseDistrictVO catMenu : allMenu) {
            if (catMenu.getDistrictId().equals(parentId)) {
                allChildCatIds.add(catMenu.getDistrictId());
                parentId = catMenu.getDistrictParentId();
                break;
            }
        }

        if (!parentId.equals(0)) {
            getDistrictChild3(allMenu, parentId, allChildCatIds);
        }

        return allChildCatIds;
    }
    @Override
    public ResponseResult queryVideo(ManageShopVideoParamDTO param) {
        // 权限判断
        UserPermissionsResult userPermissionsResult = UserService.judgePermissions(PermissionsConstant.SERLLER_ALBUM,
                param.getToken());

        if (!userPermissionsResult.getFlag()) {
            return ResponseResult.fail(10086, "没有权限");
        }
        param.setShopId(userPermissionsResult.getShopId());
        Page<ManageShopVideoListVO> page = new Page<>(param.getPage(),param.getLimit());
        IPage<ManageShopVideoListVO> videoList = this.baseMapper.selectVideoList(page,param);
        return ResponseResult.success(PageUtils.getPage(videoList));
    }

    @Override
    public ResponseResult allRegularStore(ShopBaseListQueryDTO param) {
        UserInfoVO userInfo = ParseTokenUtils.getPlatformUser(param.getToken());
        if(null != userInfo){
            try {
                Map data = ParseMapUtils.beanToMap(param);
                //查询所有非供应商店铺
                IPage<ShopBaseListQueryVO> page = this.baseMapper.allRegularStore(new Query<ShopBaseListQueryVO>().getPage(data),param);
                List<ShopBaseListQueryVO> records = page.getRecords();
                for (ShopBaseListQueryVO record : records) {
                    String shopAddress = getAddress(String.valueOf(record.getShopProvince()),String.valueOf(record.getShopCity()),String.valueOf(record.getShopCity()));
                    record.setShopLocation(shopAddress);
                    shopAddress = shopAddress + record.getShopAddress();
                    record.setShopAddress(shopAddress);
                }
                page.setRecords(records);
                return ResponseResult.success(PageUtils.getPage(page));
            } catch (IllegalAccessException e) {
                return ResponseResult.fail(BizCodeEnume.SYSTEM_ERROR);
            }
        }
        return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
    }

    @Override
    public ResponseResult selectretention(Map<String, Object> map) {
        String token = String.valueOf(map.get("token"));
        UserInfoVO userInfo=ParseTokenUtils.getUserInfoByToken(token);
        if (userInfo == null){
            return ResponseResult.fail(BizCodeEnume.TOKEN_IS_INVALID);
        }
        //查询质保金说明
        BaseSysConfigsVO pos = this.baseMapper.selectByConfigType("platform_operation_specifications");
        if (pos == null){
            return ResponseResult.fail(0, "查询失败");
        }

        PlatformoperationVO platform = JSONObject.parseObject(pos.getConfigValue(), PlatformoperationVO.class);
        //查询质保金信息
        ShopBaseEntity selectretention = this.baseMapper.selectById(userInfo.getShopId());
        selectretention.setRetentionIllustrate(platform.getExplanation());//质保金说明

        selectretention.setUserMobile(userInfo.getUserMobile());

        //查询账户余额
        String balance = this.baseMapper.queryAccountBalance(userInfo.getUserId());
        selectretention.setAccountBalance(balance);

        //查询本月罚款金额
        Map monthTime = DateUtils.getMonthTime();
        Map<String, Object> map1 = new HashMap<>();
        map1.put("start",monthTime.get("startDate"));
        map1.put("end",monthTime.get("endDate"));
        map1.put("shopId",userInfo.getShopId());


        //查询本月罚款额度
        String s = this.baseMapper.querymonthFine(map1);
        if (s == null || s == ""){
            s = "0";
        }
        selectretention.setMonthFine(new BigDecimal(s));

        return ResponseResult.success(selectretention);
    }

    @Override
    public ResponseResult queryshop(Map<String, Object> map) {
        HashMap<Object, Object> hashMap = new HashMap<>();
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_PLATFORM_TOKEN_USER+ map.get("token"));

        if (!isExistToken) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        if (StringUtil.isEmpty(String.valueOf(map.get("startTime")))){
            map.put("startTime",null);
        }
        if (StringUtil.isEmpty(String.valueOf(map.get("endTime")))){
            map.put("endTime",null);
        }

        IPage<ShopBaseEntity> page=this.baseMapper.queryshop(new Query<ShopBaseEntity>().getPage(map),
                map);
        return ResponseResult.success(PageUtils.getPage(page));
    }

    @Override
    public ResponseResult queryshopExp(Map<String, Object> map) {
        HashMap<Object, Object> hashMap = new HashMap<>();
        boolean isExistToken = RedisUtil.exists(YFConfig.YF_PLATFORM_TOKEN_USER + String.valueOf(map.get("token")));

        if (!isExistToken) {
            return ResponseResult.fail(BizCodeEnume.INSUFFICIENT_PERMISSIONS);
        }
        if (StringUtil.isEmpty(String.valueOf(map.get("startTime")))){
            map.put("startTime",null);
        }
        if (StringUtil.isEmpty(String.valueOf(map.get("endTime")))){
            map.put("endTime",null);
        }
        IPage<ShopBaseEntity> page=this.baseMapper.queryshop(new Query<ShopBaseEntity>().getPage(map),
                map);

        String[] title = {"店铺名称", "基础额度", "违规风险额度", "质保金当前余额", "待补缴质保金", "创建时间", "质保金状态"};

        List<Map<String, String>> list = Lists.newArrayList();
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for (ShopBaseEntity res : page.getRecords()) {
            HashMap<String, String> map2 = com.google.common.collect.Maps.newHashMap();
            map2.put("店铺名称", res.getShopName());
            map2.put("基础额度", res.getRetentionMoneyLimit().toString());
            map2.put("违规风险额度", res.getAccumulatedCompensation().toString());
            map2.put("质保金当前余额", res.getRetentionMoneyBalance().toString());
            map2.put("待补缴质保金", res.getRetentionMoneyPayment().toString());
            map2.put("创建时间", format.format(res.getShopCreateTime()));
            //质保金状态 0 无需缴纳 1 已缴纳 2 请及时补充 3 即将限权 4 已限权
            if (res.getRetentionStatus() != null && res.getRetentionStatus() == 0){
                map2.put("质保金状态", "无需缴纳");
            }else if (res.getRetentionStatus() != null && res.getRetentionStatus() == 1){
                map2.put("质保金状态", "已缴纳");
            }else if (res.getRetentionStatus() != null && res.getRetentionStatus() == 2){
                map2.put("质保金状态", "请及时补充");
            }else if (res.getRetentionStatus() != null && res.getRetentionStatus() == 3){
                map2.put("质保金状态", "即将限权");
            }else if(res.getRetentionStatus() != null && res.getRetentionStatus() == 4){
                map2.put("质保金状态", "已限权");
            }else{
                map2.put("质保金状态", "");
            }

            list.add(map2);

        }
        // excel文件名
        Map<String/* 此处的key为每个sheet的名称，一个excel中可能有多个sheet页 */, List<Map<String/* 此处key对应每一列的标题 */, String>>/*
         */> map1 = Maps
                .newHashMap();
        map1.put("测试合并数据", list);
        String url = ExcelsUtil.createExcel(title, map1, new int[]{16}/* 此处数组为需要合并的列，可能有的需求是只需要某些列里面相同内容合并 */);

        return ResponseResult.success(url);
    }


}
